// 引入工具类
const { articleApi } = require('../../utils/api')
const { formatTime } = require('../../utils/dateUtils')
const { newsStore } = require('../../utils/store')
const { extractImageFromHtml } = require('../../utils/imageUtils')

Page({
  data: {
    newsList: [],
    loading: false,
    finished: false,
    refreshing: false,
    error: false,
    selectedCategory: 0,
    selectedSort: 0,
    categories: [],
    sections: [],
    pageSize: 10,
    currentPage: 1,
    totalPages: 0,
    categoryOptions: [{ text: '全部分类', value: 0 }],
    sortOptions: [
      { text: '最新发布', value: 0 },
      { text: '最多阅读', value: 1 }
    ]
  },

  onLoad() {
    console.log('新闻列表页面加载')
    this.fetchCategories()
    this.fetchSections()
    this.loadNews(true)
  },

  onShow() {
    console.log('新闻列表页面显示')
  },

  // 获取分类列表
  async fetchCategories() {
    try {
      const response = await articleApi.getAllCategories()
      console.log('分类API响应:', response)

      const data = response.data || response || []
      const categoryOptions = [
        { text: '全部分类', value: 0 },
        ...data.map((item, index) => ({
          text: item.name || item.categoryName || item,
          value: index + 1
        }))
      ]

      this.setData({
        categories: data.map(item => item.name || item.categoryName || item),
        categoryOptions
      })

      // 保存到全局状态
      newsStore.setCategories(this.data.categories)

    } catch (error) {
      console.error('获取分类失败:', error)
      wx.showToast({
        title: '获取分类失败',
        icon: 'error'
      })
    }
  },

  // 获取学院列表
  async fetchSections() {
    try {
      const response = await articleApi.getAllSections()
      console.log('学院API响应:', response)

      const data = response.data || response || []
      this.setData({
        sections: data.map(item => item.name || item.sectionName || item)
      })

      // 保存到全局状态
      newsStore.setSections(this.data.sections)

    } catch (error) {
      console.error('获取学院列表失败:', error)
      // 学院列表不是必需的，失败时不显示错误提示
    }
  },

  // 加载新闻数据
  async loadNews(isRefresh = false) {
    try {
      if (isRefresh) {
        this.setData({
          currentPage: 1,
          newsList: [],
          finished: false,
          error: false
        })
      }

      this.setData({ loading: true })

      // 构建请求参数
      const params = {
        limit: this.data.pageSize,
        page: this.data.currentPage
      }

      let response
      // 根据选择的分类获取数据
      if (this.data.selectedCategory > 0 && this.data.categories.length > 0) {
        const categoryName = this.data.categories[this.data.selectedCategory - 1]
        response = await articleApi.getArticlesByCategory(
          categoryName,
          this.data.currentPage,
          this.data.pageSize
        )
      } else {
        response = await articleApi.getArticleList(params)
      }

      console.log('新闻列表API响应:', response)

      let newsList = []
      let rawList = []

      // 处理不同的响应格式，与mobile-vant保持一致
      if (response && response.code === 200 && response.data) {
        if (Array.isArray(response.data)) {
          rawList = response.data
        } else if (response.data.list && Array.isArray(response.data.list)) {
          rawList = response.data.list
        } else if (response.data.records && Array.isArray(response.data.records)) {
          rawList = response.data.records
        }
      } else if (Array.isArray(response)) {
        rawList = response
      } else if (response && response.list && Array.isArray(response.list)) {
        rawList = response.list
      } else if (response && response.data && Array.isArray(response.data.records)) {
        rawList = response.data.records
      }

      console.log('解析后的原始数据列表:', rawList)

      if (Array.isArray(rawList) && rawList.length > 0) {
        newsList = rawList.map(item => {
          const newsItem = {
            newsId: item.news_id || item.newsId || item.id,
            id: item.news_id || item.newsId || item.id,
            title: item.title || '无标题',
            contentPreview: this.generateSummary(item.content_text || item.contentText || ''),
            contentText: item.content_text || item.contentText || '',
            category: item.category || '校园新闻',
            section: item.section || '',
            pubTime: item.pub_time || item.pubTime,
            formattedTime: formatTime(item.pub_time || item.pubTime),
            image: this.extractImage(item.content_html || item.contentHtml || ''),
            imageUrl: this.extractImage(item.content_html || item.contentHtml || '')
          }
          console.log('处理后的新闻项:', newsItem)
          return newsItem
        })

        console.log('最终处理的新闻列表:', newsList)

        // 检查是否还有更多数据
        const hasMore = newsList.length >= this.data.pageSize
        const currentList = isRefresh ? newsList : this.data.newsList.concat(newsList)

        this.setData({
          newsList: currentList,
          currentPage: this.data.currentPage + 1,
          finished: !hasMore,
          loading: false,
          error: false
        })

        console.log('页面数据已更新，当前新闻数量:', currentList.length)

        // 保存到全局状态
        if (isRefresh) {
          newsStore.addNewsToList(newsList, false)
        } else {
          newsStore.addNewsToList(newsList, true)
        }
      } else {
        console.warn('未找到有效的新闻数据')
        this.setData({
          loading: false,
          finished: true,
          error: false
        })
      }

    } catch (error) {
      console.error('获取新闻列表失败:', error)
      this.setData({
        loading: false,
        error: true
      })
      wx.showToast({
        title: '获取新闻失败',
        icon: 'error'
      })
    }
  },

  // 生成摘要
  generateSummary(content) {
    if (!content) return '无内容摘要'
    // 移除HTML标签
    const text = content.replace(/<[^>]*>/g, '')
    return text.length > 100 ? text.substring(0, 100) + '...' : text
  },

  // 提取图片
  extractImage(htmlContent) {
    return extractImageFromHtml(htmlContent)
  },

  // 下拉刷新
  async onRefresh() {
    this.setData({ refreshing: true })
    await this.loadNews(true)
    this.setData({ refreshing: false })
    wx.showToast({
      title: '刷新成功',
      icon: 'success'
    })
  },

  // 上拉加载更多
  async onLoad() {
    if (this.data.finished || this.data.loading) return
    await this.loadNews(false)
  },

  // 处理分类变化
  handleCategoryChange(event) {
    const selectedCategory = event.detail
    console.log('分类变化:', selectedCategory)
    this.setData({ selectedCategory })
    this.onRefresh()
  },

  // 处理排序变化
  handleSortChange(event) {
    const selectedSort = event.detail
    console.log('排序变化:', selectedSort)
    this.setData({ selectedSort })
    this.onRefresh()
  },

  // 跳转到新闻详情
  goToDetail(event) {
    try {
      const newsId = event.currentTarget.dataset.newsId
      console.log('跳转新闻详情:', newsId)

      if (!newsId) {
        wx.showToast({
          title: '文章ID无效',
          icon: 'error'
        })
        return
      }

      // 添加到历史记录
      const newsItem = this.data.newsList.find(item =>
        (item.newsId || item.id) == newsId
      )

      if (newsItem) {
        const app = getApp()
        app.addHistory(newsItem)
      }

      wx.navigateTo({
        url: `/pages/news/detail/detail?id=${newsId}`
      })

    } catch (error) {
      console.error('跳转新闻详情失败:', error)
      wx.showToast({
        title: '跳转失败',
        icon: 'error'
      })
    }
  }
})
